Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor


Topic: Prime program implemented in console Visual Basic

February 18, 2016


Module PrimeConsoleSubroutines

    Private Const LIMIT = 1000000

    Sub Main()

        Dim number As Integer
        Dim prime As Boolean

        System.Console.OutWriteLines("Please enter a number to see if it is a prime:")

        If Integer.TryParse(System.Console.In.ReadLine(), number) = 0 Then

            System.Console.Out.WriteLine("Invalid Input")

        ElseIf number < 0 Or number > 1000000 Then

            System.Console.Out.WriteLine("Number out of range.")

        Else

            prime = determineIfPrime(number)

            If prime = True Then
                System.Console.Out.WriteLine(number & " is a prime.")
            Else
                System.Console.Out.WriteLine(number & " is not a prime.")
            End If

        End If

    End Sub


    Function determineIfPrime(ByVal number) As Boolean

        Dim prime As Boolean
        Dim divisor As Integer
        Dim remainder As Integer

        prime = True

        If number = 0 Or number = 1 Then

            prime = False

        Else

            divisor = 2

            remainder = modulo(number, divisor)

            If remainder = 0 Then
                prime = False
            End If

            divisor = divisor + 1

            While prime = True And divisor <= Math.Sqrt(number)

                remainder = modulo(number, divisor)

                If remainder = 0 Then
                    prime = False
                End If

                divisor = divisor + 2

            End While

        End If

        Return prime

    End Function


    Function modulo(ByVal number, ByVal divisor) As Integer
        Dim intermediate As Integer
        Dim remainder As Integer

        intermediate = number

        While intermediate >= divisor
            intermediate = intermediate - divisor
        End While

        remainder = intermediate

        Return remainder

    End Function

End Module



Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor